﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace FilesUploader.Web
{
    public partial class DownloadUploadPhotos : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["type"] == "U")
            {
                using (StreamReader sr = new StreamReader(Request.InputStream))
                {
                    String[] content = sr.ReadToEnd().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (content.Length == 3)
                    {
                        SaveChunk(content);
                    }
                    else if (content.Length == 4)
                    {
                        RenameFile(content);
                    }
                    else
                    {
                        throw new InvalidOperationException("Invalid InputStream content");
                    }
                }
            }
        }

        private string DestDirectory(string content0)
        {
            return Path.Combine(Request.MapPath("public"), content0 == "\\" ? "" : content0);
        }

        private void RenameFile(String[] content)
        {
            string directory = DestDirectory(content[0]);
            CheckCreateDir(directory);

            String file = Path.Combine(directory, content[1]);

            string tempFile = file + ".psx";
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            File.Move(tempFile, file);
        }

        private void SaveChunk(String[] content)
        {
            string directory = DestDirectory(content[0]);
            CheckCreateDir(directory);

            String file = Path.Combine(directory, content[1]);

            Byte[] bytes = new Byte[content[2].Length];
            bytes = Convert.FromBase64String(content[2]);
            string tempFile = file + ".psx";
            FileStream fs = new FileStream(tempFile, FileMode.Append);
            fs.Write(bytes, 0, bytes.GetLength(0));
            fs.Close();
            Response.Write(content[1] + "|");
        }

        //private string CheckDeleteThumbFile(string directory, string imageFile)
        //{
        //    string thumbPath = Path.Combine(directory, "Thumb");
        //    CheckCreateDir(thumbPath);

        //    string thumbFile = Path.Combine(thumbPath, imageFile);
        //    if (File.Exists(thumbFile))
        //    {
        //        File.Delete(thumbFile);
        //    }
        //    return thumbFile;
        //}

        private void CheckCreateDir(string dir)
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }
    }
}